//
//  ShopCartManager.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/9/8.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "ShopCartManager.h"

#import<CommonCrypto/CommonDigest.h>

#import "Toast.h"

@interface ShopCartManager ()

/**货物*/
@property(nonatomic,strong)NSMutableArray * goods;

@end
@implementation ShopCartManager
+(instancetype)shareManager{
    static ShopCartManager * manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[[self class] alloc] _init];
    });
    return manager;
}

-(id)_init{
    if(self = [super init]){
        self.goods = [NSMutableArray array];
        self.selectedProduct = [NSMutableArray array];
    }
    return self;
}


+(void)setDelegate:(id<ShopCartManagerDelegate>)delegate{
    [ShopCartManager shareManager].delegate = delegate;
}






+(void)addProduct:(Product *)product complete:(void (^)(NSArray *))complete{
     ShopCartManager * manager = [ShopCartManager shareManager];
    [[LXDataManager manager] addShopCartWithProduct:product complete:^(BOOL success, id res) {
        if(success){
            if([[ShopCartManager shareManager].goods indexOfObject:product]==NSNotFound){
                product.numberInShopCart = 1;
                [[ShopCartManager shareManager].goods addObject:product];
                if(complete)complete([ShopCartManager shareManager].goods);
            }
            else{
                product.numberInShopCart = product.numberInShopCart+1;
                if(complete)complete([ShopCartManager shareManager].goods);
            }
            if([manager.selectedProduct indexOfObject:product]==NSNotFound){
                
            }else{
                if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
                    [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
                }
            }
        }
    }];
}

+(void)removeProduct:(Product *)product complete:(void (^)(NSArray *))complete{
     ShopCartManager * manager = [ShopCartManager shareManager];
    [[LXDataManager manager] delShopCartWithProduct:product complete:^(BOOL success, id res) {
        if(success){
            if([[ShopCartManager shareManager].goods indexOfObject:product]==NSNotFound){
                product.numberInShopCart = 0;
                if(complete)complete([ShopCartManager shareManager].goods);
            }
            else{
                product.numberInShopCart = product.numberInShopCart-1;
                if(product.numberInShopCart==0){
                    [[ShopCartManager shareManager].goods removeObject:product];
                    [ShopCartManager deleteSelectedProduct:product];
                    if(complete)complete([ShopCartManager shareManager].goods);
                }else{
                    if(complete)complete([ShopCartManager shareManager].goods);
                }
            }
            if([manager.selectedProduct indexOfObject:product]==NSNotFound){
                
            }else{
                if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
                    [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
                }
            }
        }
    }];
}

+(void)removeAllProduct:(Product *)product complete:(void (^)(NSArray *))complete{
    ShopCartManager * manager = [ShopCartManager shareManager];
    [[LXDataManager manager] delAllShopCartWithProduct:product complete:^(BOOL success, id res) {
        if(success){
            if([manager.selectedProduct indexOfObject:product]!=NSNotFound){
                [manager.selectedProduct removeObject:product];
                product.numberInShopCart = 0;
                if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
                    [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
                }
            }
            if([manager.goods indexOfObject:product]!=NSNotFound){
                [manager.goods removeObject:product];
                if(complete)complete(manager.goods);
            }else{
                if(complete)complete(manager.goods);
            }
        }
    }];
}
+(void)getAllProductComplete:(void (^)(NSArray *))complete{
    [[LXDataManager manager] getShopCartListComplete:^(BOOL success, id res) {
        if(success){
            NSMutableArray * goods = [ShopCartManager shareManager].goods;
            NSMutableArray * tempArray = [NSMutableArray array];
            [tempArray addObjectsFromArray:goods];
            for (Product * netp in res) {
                BOOL haveFound = NO;
                for (Product * localp in goods) {
                    if([netp.product_id isEqualToString:localp.product_id]){
                        haveFound = YES;
                    }
                }
                if(!haveFound){
                    [tempArray addObject:netp];
                }
            }
            [goods removeAllObjects];
            [goods addObjectsFromArray:tempArray];
            if(complete)complete(goods);
        }else{
            if(complete)complete([NSArray new]);
        }
    }];
}



+(void)addSelectedProduct:(Product *)product{
    ShopCartManager * manager = [ShopCartManager shareManager];
    if([manager.selectedProduct indexOfObject:product] == NSNotFound){
        [manager.selectedProduct addObject:product];
    }else{
        product.numberInShopCart = product.numberInShopCart+1;
    }
    if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
        [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
    }
}

+(void)removeSelectedProduct:(Product *)product{
    ShopCartManager * manager = [ShopCartManager shareManager];
    if([manager.selectedProduct indexOfObject:product] == NSNotFound){
        
    }else{
        product.numberInShopCart = product.numberInShopCart-1;
        if(product.numberInShopCart == 0){
            [manager.selectedProduct removeObject:product];
        }
    }
    if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
        [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
    }
}

+(CGFloat)calculateSelectedPrice{
    ShopCartManager * manager = [ShopCartManager shareManager];
    CGFloat totalPrice = 0.f;
    for (Product * p in manager.selectedProduct) {
        CGFloat price = [p.specialprice floatValue];
        totalPrice+=price*p.numberInShopCart;
    }
    return totalPrice;
}

+(void)deleteSelectedProduct:(Product *)product{
    ShopCartManager * manager = [ShopCartManager shareManager];
    [[ShopCartManager shareManager].selectedProduct removeObject:product];
    if(manager.delegate&&[manager.delegate respondsToSelector:@selector(ShopCartManager:didUpDateSelectedProductPrice:)]){
        [manager.delegate ShopCartManager:manager didUpDateSelectedProductPrice:[ShopCartManager calculateSelectedPrice]];
    }
}


+(NSInteger)numberOfProducts{
    NSInteger all = 0;
    ShopCartManager * manager = [ShopCartManager shareManager];
    for (Product *p in manager.selectedProduct) {
        all+=p.numberInShopCart;
    }
    return all;
}

+(NSString*)format{
    NSMutableString * mStr = [NSMutableString string];
    ShopCartManager * manager = [ShopCartManager shareManager];
    [manager.selectedProduct enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            Product * model = obj;
            if(idx != manager.selectedProduct.count-1)
            {
                NSString * str = [NSString stringWithFormat:@"%@-%@,",model.product_id,model.cart_goods_num];
                [mStr appendString:str];
            }
            else
            {
                NSString * str = [NSString stringWithFormat:@"%@-%@",model.product_id,model.cart_goods_num];
                [mStr appendString:str];
            }
    }];
    return mStr;
}

+(NSString*)formatName{
    NSMutableString * mStr = [NSMutableString string];
    ShopCartManager * manager = [ShopCartManager shareManager];
    [manager.selectedProduct enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        Product * model = obj;
        if(idx != manager.selectedProduct.count-1)
        {
            NSString * str = [NSString stringWithFormat:@"%@,",model.name];
            [mStr appendString:str];
        }
        else
        {
            NSString * str = [NSString stringWithFormat:@"%@",model.name];
            [mStr appendString:str];
        }
    }];
    return mStr;
}


+(void)calculateSelectedPriceWithGreenBeanComplete:(void (^)(CGFloat,CGFloat,CGFloat))complete{
    LXUser * user = [LXUser shareUser];
    __block CGFloat discountGreenBean = 0;
    __block CGFloat totalPrice = 0;
    [[LXDataManager manager] getGreenBeanWithComplete:^(BOOL success, id res) {
        if(success){
            user.bean_nums = res[@"data"][@"beannums"];
            [[ShopCartManager shareManager].selectedProduct enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                Product * p = (Product *)obj;
                discountGreenBean+=([p.pointdeduction floatValue]*100)*p.numberInShopCart;
                totalPrice += [p.specialprice floatValue]*p.numberInShopCart;
            }];
            if(complete)complete(totalPrice,discountGreenBean,[user.bean_nums floatValue]);
        }
    }];
}

+(NSInteger)selectedCount{
    NSInteger nnn = 0;
    for (Product * p in [ShopCartManager shareManager].selectedProduct) {
        nnn+=p.numberInShopCart;
    }
    return nnn;
}

+(void)payForOrderID:(NSString *)orderid price:(CGFloat)price desc:(NSString *)desc complete:(void (^)(BOOL))complete{
    NSDictionary * param = @{@"user_id":[LXUser shareUser].user_id,@"client":@"ios"};
    [[LXDataManager manager] getAliPayInfoWithPrama:param Complete:^(BOOL success, id res) {
        if(success){
            NSString *partner = res[@"partner"];
            NSString *seller = res[@"seller_id"];
            NSString *privateKey = res[@"privateKey"];
            if(partner.length == 0){
                [Toast showWithMessege:@"商家信息获取失败" duration:2];
                return;
            }
            if(seller.length == 0){
                [Toast showWithMessege:@"商家信息获取失败" duration:2];
                return;
            }
            if(privateKey.length == 0){
                [Toast showWithMessege:@"商家信息获取失败" duration:2];
                return;
            }
            Order *order = [[Order alloc] init];
            order.partner = partner;
            order.sellerID = seller;
            
            order.outTradeNO = orderid;
            //    order.subject = product.subject; //商品标题
            order.subject = desc;
            
            //    order.body = product.body; //商品描述
            order.body = @"绿稀全球购";
            
            // order.totalFee = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
            //    order.totalFee = [NSString stringWithFormat:@"%.2f",[self.commodities totalPrice]];
            
            
            order.totalFee = [NSString stringWithFormat:@"%.2f",price];
            
            order.notifyURL =  @"https://www.lx139.com"; //回调URL
            
            order.service = @"mobile.securitypay.pay";
            order.paymentType = @"1";
            order.inputCharset = @"utf-8";
            order.itBPay = @"30m";
            order.showURL = @"m.alipay.com";
            
            //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
            NSString *appScheme = @"com.lx139.LvXiShopping";
            
            //将商品信息拼接成字符串
            NSString *orderSpec = [order description];
            //    NSLog(@"orderSpec = %@",orderSpec);
            
            //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
            id<DataSigner> signer = CreateRSADataSigner(privateKey);
            NSString *signedString = [signer signString:orderSpec];
            //将签名成功字符串格式化为订单字符串,请严格按照该格式
            NSString *orderString = nil;
            if (signedString != nil) {
                orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                               orderSpec, signedString, @"RSA"];
                
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"%@",resultDic);
                    
                    if([resultDic[@"resultStatus"] integerValue]==9000){
                        NSString * comstr = [NSString stringWithFormat:@"%@%@%.2f%.0f%@",User_id,orderid,price,0.0,OrderPublickey];
                        comstr = [comstr sha1String];
                        NSLog(@"%.2f",price);
                        [[LXDataManager manager] upDataOrderStatuWithPrama:@{@"user_id":User_id,@"order_id":orderid,@"payment":@"2",@"total_fee":[NSString stringWithFormat:@"%.2f",price],@"decou":@"0",@"comstr":comstr} complete:^(BOOL success, id res) {
                            if(success){
                                [Toast showWithMessege:@"订单成功完成支付!" duration:2];
                            }
                        }];
                        if(complete)complete(YES);
                    }
                    else
                    {
                        if(complete)complete(NO);
                    }
                }];
            }
        }else{
            [Toast showWithMessege:@"数据获取失败" duration:2];
        }
    }];

//    // 1.添加写partner/seller/privateKey,签约后获得
//    NSString *partner = @"2088912163137355";
//    NSString *seller = @"sjt13955555@126.com";
//    NSString *privateKey = AliPayPrivateKey;
//    
////    #define OrderPublickey @"roduwdfghjklkjbxcvbnmrtghjghjmk"
//    // 2.生成订单
//    // 2.1.创建订单
//    
//    /*
//     *生成订单信息及签名
//     */
//    //将商品信息赋予AlixPayOrder的成员变量
//    Order *order = [[Order alloc] init];
//    order.partner = partner;
//    order.sellerID = seller;
//    
//    order.outTradeNO = orderid;
//    //    order.subject = product.subject; //商品标题
//    order.subject = desc;
//    
//    //    order.body = product.body; //商品描述
//    order.body = @"绿稀全球购";
//    
//    // order.totalFee = [NSString stringWithFormat:@"%.2f",product.price]; //商品价格
//    //    order.totalFee = [NSString stringWithFormat:@"%.2f",[self.commodities totalPrice]];
//    
//    
//    order.totalFee = [NSString stringWithFormat:@"%.2f",price];
//    
//    order.notifyURL =  @"https://www.lx139.com"; //回调URL
//    
//    order.service = @"mobile.securitypay.pay";
//    order.paymentType = @"1";
//    order.inputCharset = @"utf-8";
//    order.itBPay = @"30m";
//    order.showURL = @"m.alipay.com";
//    
//    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
//    NSString *appScheme = @"com.lx139.LvXiShopping";
//    
//    //将商品信息拼接成字符串
//    NSString *orderSpec = [order description];
//    //    NSLog(@"orderSpec = %@",orderSpec);
//    
//    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
//    id<DataSigner> signer = CreateRSADataSigner(privateKey);
//    NSString *signedString = [signer signString:orderSpec];
//    //将签名成功字符串格式化为订单字符串,请严格按照该格式
//    NSString *orderString = nil;
//    if (signedString != nil) {
//        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
//                       orderSpec, signedString, @"RSA"];
//        
//        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//            NSLog(@"%@",resultDic);
//            
//            if([resultDic[@"resultStatus"] integerValue]==9000){
//                NSString * comstr = [NSString stringWithFormat:@"%@%@%.2f%.0f%@",User_id,orderid,price,0.0,OrderPublickey];
//                comstr = [comstr sha1String];
//                NSLog(@"%.2f",price);
//                [[LXDataManager manager] upDataOrderStatuWithPrama:@{@"user_id":User_id,@"order_id":orderid,@"payment":@"2",@"total_fee":[NSString stringWithFormat:@"%.2f",price],@"decou":@"0",@"comstr":comstr} complete:^(BOOL success, id res) {
//                    if(success){
//                        if(success){
//                            
//                        }
//                    }
//                }];
//                if(complete)complete(YES);
//            }
//            else
//            {
//                if(complete)complete(NO);
//            }
//        }];
//    }

}
@end
